<template>
  <view class="product-selector">
    <button class="close-btn" @click="$emit('close')">×</button>
    <view class="quantity">
      <text class="label">数量</text>
      <view class="quantity-control">
        <button @click="decreaseQuantity">-</button>
        <text>{{ quantity }}</text>
        <button @click="increaseQuantity">+</button>
      </view>
    </view>
    <view class="actions">
      <button class="cart-button" @click="addToCart">加入购物车</button>
      <button class="buy-button" @click="buyNow">立即购买</button>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ProductSelector',
  data() {
    return {
      quantity: 1
    }
  },
  methods: {
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity -= 1;
      }
    },
    increaseQuantity() {
      this.quantity += 1;
    },
    addToCart() {
      const cartItem = {
        quantity: this.quantity
      };
      // 将商品添加到购物车（假设使用 Vuex 存储购物车信息）
      this.$store.commit('addToCart', cartItem);
      this.$emit('close');
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    },
    buyNow() {
      const orderItem = {
        quantity: this.quantity
      };
      // 跳转到订单页面并传递订单信息
      uni.navigateTo({
        url: `/pages/payment/payment?item=${encodeURIComponent(JSON.stringify(orderItem))}`
      });
    }
  }
}
</script>

<style scoped>
.close-btn {
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  border-radius: 50%;
  border: none;
  background-color: #f5f5f5;
  font-size: 30rpx;
  color: #999;
}
.product-selector {
  padding: 16px;
}

.quantity {
  margin-bottom: 16px;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-control button {
  padding: 0 12px;
  font-size: 16px;
}

.actions {
  display: flex;
  justify-content: space-between;
}

.cart-button {
  background-color: orange;
  color: white;
  padding: 10px 30px;
  font-size: 16px;
  border-radius: 4px;
  margin-right: 8px;
}

.buy-button {
  background-color: red;
  color: white;
  padding: 10px 30px;
  font-size: 16px;
  border-radius: 4px;
}
</style>
